/*
 * name: download.js
 * version: v0.0.1
 * update: build
 * date: 2015-10-22
 */
define('download', function(require, exports, module) {
	//var $ = require('jquery');
	var def = {
		path: "wgt://myspace/down/",
		name: "",
		onCreate: function() {
			appcan.window.openToast('正在下载', '2000', 8);
		},
		onCreateError: function() {
			appcan.window.openToast('创建下载失败', '2000', 8);
		},
		onStatus: function(percent) {
			appcan.window.openToast('正在下载:' + percent + '%', '2000', 8);
		},
		success: function(filePath) {

		},
		error: function() {
			appcan.window.openToast('创建下载进程失败', '2000');
		}
	};
	var download = function(remotePath, option) {
		var randOpId = Math.floor(Math.random() * (1000 + 1)),
			opt = $.extend(def, option || {}),
			filePath, cbCreateDownloader_func;
		if (!opt.name) {
			opt.name = randOpId
		};
		filePath = opt.path + opt.name;
		cbCreateDownloader_func = function(opId, dataType, data) {
			if (data == 0) {
				uexDownloaderMgr.download(randOpId, remotePath, filePath, 1);
				return opt.onCreate();
			} else {
				return opt.onCreateError();
			}
		};
		uexDownloaderMgr.onStatus = function(opId, fileSize, percent, status) {
			switch (status) {
				case 0:
					opt.onStatus(percent);
					break;
				case 1:
					appcan.window.openToast('下载完成', '2000', 8);
					uexDownloaderMgr.closeDownloader(randOpId);
					//TODO:filePath
					opt.success(filePath);
					break;
				case 2:
					appcan.window.openToast('下载失败', '2000', 8);
					uexDownloaderMgr.closeDownloader(randOpId);
					opt.error();
					break;
			}
		};
		uexDownloaderMgr.createDownloader(randOpId);
		uexDownloaderMgr.cbCreateDownloader = cbCreateDownloader_func;
	};
	module.exports = download;
});